package com.example.bookstore.controller.admin;

import com.example.bookstore.entity.Book;
import com.example.bookstore.entity.OrderLink;
import com.example.bookstore.entity.Ordered;
import com.example.bookstore.service.BookService;
import com.example.bookstore.service.OrderService;
import com.example.bookstore.service.PeopleService;
import com.example.bookstore.util.AliOssUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/admin")
public class AdminController {

    @Resource
    private BookService bookService;

    @Resource
    private AliOssUtil aliOssUtil;

    @Resource
    private PeopleService peopleService;

    @Resource
    private OrderService orderService;


    @RequestMapping("/add")
    public String add(MultipartFile file,Book book){

        try {
            //原始文件名
            String originalFilename = file.getOriginalFilename();
            //截取原始文件名的后缀
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            //构造新文件名
            String objectName = UUID.randomUUID().toString();
            objectName=objectName+extension;
            //文件请求路径
            String Path = aliOssUtil.upload(file.getBytes(), objectName);

            book.setImage(Path);
        } catch (IOException e) {
            e.printStackTrace();
        }

        bookService.add(book);

        return "/findAll";
    }


    @RequestMapping("/deleteById")
    public String deleteById(Integer id){

        Integer row = peopleService.deleteBook(id);

        return "redirect:/findAll";
    }

    /**
     * 查询所有订单admin
     * @return
     */
    @RequestMapping("/queryAllOrder")
    public String queryAllOrder(Model model){

        //查询ordered主订单信息，每一条信息代表一个订单
        List<Ordered> ordereds = orderService.findAllOrder();

        model.addAttribute("ordereds",ordereds);

        //查询每条订单对应的子商品

        for (Ordered ordered:ordereds){
            //循环获取每条订单的id
            Integer orderedId = ordered.getId();
            //获取该条订单的子商品
            List<OrderLink> list = orderService.findOrderLinks(orderedId);

            String oid = orderedId.toString();
            String AttributeName = "list"+oid;  // list1

            //第n条订单商品信息
            model.addAttribute(AttributeName,list);
        }

        return "/pages/ordered.jsp";
    }

}
